<?php
class User_interface extends CI_Model {
	public function __construct() {
		parent::__construct();
		$this->load->model('Comm');
	}

	//return failed:0, success:user uid
	public function checkUserRegister($email = NULL, $nick_name = NULL) {
		if(empty($email)) $email = $this->input->get('email');
		if(empty($nick_name)) $nick_name = $this->input->get('nick_name');
		if(empty($email) && empty($nick_name)) return -5;
		if(!empty($email)) {
			$this->load->helper('email');
			if(!valid_email($email)) return 0;
			$arrResult = $this->Comm->getList('user_register', 'uid', array('email'=>$email));
			if(isset($arrResult[0]['uid']) && $arrResult[0]['uid'] > 0) {
				return $arrResult[0]['uid'];
			}
		}
		if(!empty($nick_name)) {
			$arrResult = $this->Comm->getList('user_register', 'uid', array('nick_name'=>$nick_name));
			if(isset($arrResult[0]['uid']) && $arrResult[0]['uid'] > 0) {
				return $arrResult[0]['uid'];
			}
		}
		return 0;
	}
	//return failed: email error -1, passwd error -2; success:user uid
	public function newUser() {
		$arrNewUser['email'] = $this->input->post('email');
		$arrNewUser['nick_name'] = $this->input->post('nick_name');
		if(empty($arrNewUser['email']) || empty($arrNewUser['nick_name'])) return -5;
		$checkUser = $this->checkUserRegister($arrNewUser['email'], $arrNewUser['nick_name']);
		if($checkUser > 0) return -1;//用户已经存在
		if($checkUser < 0) return -5;//empty email or nick_name
		$__HASH_ =  $this->input->post($this->config->item('csrf_token_name'));
		$__HASH_COOKIE = $this->input->cookie($this->config->item('csrf_cookie_name'));
		if(!empty($__HASH_) && $__HASH_ != $__HASH_COOKIE) return -4;//验证不通过，非法递交
		$arrNewUser['passwd'] = $this->input->post('password1');
		if($arrNewUser['passwd'] != $this->input->post('password2')) return -2;//2次输入的密码不等
		$arrNewUser['mobile'] = $this->input->post('mobile');
		$arrNewUser['passwd'] = md5(md5($arrNewUser['passwd']) . $this->config->item('user_key'));
		if($this->db->insert('user_register', $arrNewUser)) {
			$uid = $this->db->insert_id();
			$this->db->insert('user_info', array('uid'=>$uid, 'nick_name'=>$arrNewUser['nick_name']));
			return $uid;
		}
		return -3;//插入失败
	}
}